import React, {PureComponent} from 'react';
// import { connect } from 'dva';
import style from "styled-components";
import {Alert, Steps, Upload, message, Button, Modal, Table, Icon} from 'antd';
// import TwoDimensionCode from '../../../assets/images/two_dimension_code.png';
import store from "store";

const {Step} = Steps;
import {host, systemComDepartImportDepart} from "../../../services/api";

/**
 * 导入员工基本信息
 */
export default class InitialImportEmployeeBasicInformation extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      visible: false,
      visibleFormat: false,
      uploadResponse: [],//格式正确后返回的json字符串
      dataFormat: "",//格式错误提示内容
      loading: false
    };

  }

  /******************************生命周期******************************/

  componentDidMount = () => {
  }
  componentWillReceiveProps = () => {

  }
  /******************************ajax请求******************************/
    //批量导入组织架构
  systemComDepartImportDepart = () => {
    systemComDepartImportDepart({data: JSON.stringify(this.state.uploadResponse)}).then(
      (data) => {
        this.againUpload(data.msg);
      },
      (err) => {
        console.log(err);
      }
    );
  }
  /******************************相关事件******************************/
  showModal = () => {
    this.setState({
      visible: true,
    });
  };
  handleOk = (ifError) => {
    this.setState({
      visible: false,
    });
    if (!ifError) {
      this.systemComDepartImportDepart();
    }
  };
  handleCancel = (e) => {
    this.setState({
      visible: false,
    });
  };

  againUpload = (msg = "") => {

    if (!msg.includes("导入完成")) {
      return;
    }
    let num = "";
    msg.replace(/导入条数【(.*?)】/, (match, p1) => {
      num = p1;
    });

    Modal.confirm({
      title: `您已成功导入${num}条员工信息！`,
      iconType: "check-circle",
      content: (
        <div>
          <p>若还需导入其他员工信息，请点击【继续上传】。</p>
          <p>（还可在“企业管理通讯录”里继续添加或修改员工信息）。</p>
        </div>
      ),
      okText: "下一步",
      cancelText: "继续上传",
      onOk: () => {
        this.props.nextStep();
      },
      onCancel: () => {
      }
    });
  }
  //格式错误提示框
  handleFormatOk = () => {
    this.setState({visibleFormat: false});
  }
  //下载
  handleClickLink = () => {
    return (
      <Button type="primary"
              onClick={
                () => window.open(`${host}/system/com-depart/export-depart-temp`, "_self")
              }>下载模板</Button>
    );
  };
  // 上传
  handleClickUpload = () => {
    const uploadExcel = {
      name: "xfile",
      action: `${host}/system/com-depart/get-import-depart-json`,
      headers: {
        authorization: "Basic c2Fhc3dlYjp3ZWI=",
        access_token: store.get("saas")["access_token"]
      },
      showUploadList: false,
      data: {},
    };

    const beforeUpload = file => {
      let ifError = true;
      console.log(file);
      if (file.name.indexOf("xls") === -1 && file.name.indexOf("xlsx") === -1) {
        message.error('请上传xls或xlsx文件!');
        ifError = false;
      }
      return ifError;
    };

    //上传文件
    const UploadChange = info => {
      if (!this.state.loading) {
        this.setState({
          loading: message.loading('加载中..', 0)
        })
      }
      console.log(info.file.status);
      if (info.file.status === 'uploading') {
        return;
      }
      if (info.file.status === 'done') {
        const hide = this.state.loading;
        hide();
        this.setState({loading: false});
        console.log(info.file.response.data);
        const {data, msg} = info.file.response;
        //判断格式是否正确
        //如果没有返回data，则提示msg内容
        //如果data没有数组，则是格式错误，否则为其他错误提示
        console.error(info.file.response);
        if (!data) {
          this.setState({visibleFormat: true, dataFormat: msg});
        } else {
          this.setState({uploadResponse: info.file.response.data.map((val, key) => ({...val, ...{key}}))}, () => {
            this.setState({visible: true});
          });
        }
        if (info.file.response.retType === 0) {
          // message.success(info.file.response.msg);
        }
      }
    };
    return (
      <Upload onChange={UploadChange}
              beforeUpload={beforeUpload}
              {...uploadExcel}>
        <Button type="primary">
          选择上传文件
        </Button>
      </Upload>
    );
  };

  /******************************render******************************/
    //文件上传返回数据 提示框
  renderUploadResult = () => {

    //上传结果列
    const columns = [{
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      fixed: 'left',
      width: 130,
    }, {
      title: '证件类型',
      dataIndex: 'idCardType',
      key: 'idCardType',
      width: 130,
    }, {
      title: '证件号码',
      dataIndex: 'idCardNo',
      key: 'idCardNo',
      width: 200,
    }, {
      title: '手机号',
      dataIndex: 'mobilePhone',
      key: 'mobilePhone',
      width: 140,
    }, {
      title: '部门名称',
      dataIndex: 'departName',
      key: 'departName',
      width: 160,
    }, {
      title: '角色',
      dataIndex: 'roleName',
      key: 'roleName',
      width: 160,
    }, {
      title: '入职时间',
      dataIndex: 'entryDate',
      key: 'entryDate',
      width: 160,
    }, {
      title: '校验提示',
      dataIndex: 'errorMsg',
      key: 'errorMsg',
      width: 200,
    }];

    //格式错误列展示
    let uploadResponse = JSON.parse(JSON.stringify(this.state.uploadResponse));
    //后台的为null 统一转""
    uploadResponse = uploadResponse.map(val => {
      Object.keys(val).map(v => {
        if (v === 'entryDate') {
          val[v] = val[v].slice(0, 10);
        }
        if (!val[v]) {
          val[v] = "";
        }
      });
      return val;
    });
    console.log(uploadResponse);
    //过滤，包含错误信息的数组
    const errorLength = uploadResponse.filter(val => val.errorMsg.trim() !== "");
    let ifError = errorLength.length !== 0;//判断是否包含错误信息
    let alert = "";
    if (ifError) {
      //上传失败
      uploadResponse = uploadResponse.map(val => {
        if (val.errorMsg !== "") {
          val.errorMsg = val.errorMsg.replace(/<br>/, "").trim();
        }
        return val;
      });
      alert = (
        <Alert
          message={`本次上传失败，共 ${uploadResponse.length} 条员工数据，其中有 ${errorLength.length} 条员工的信息格式校验有误。请核对，若有误，则调整 excel`}
          type="error"
          showIcon/>
      );
    } else {
      //上传成功
      alert = (
        <Alert
          message={`本次上传全部成功，共上传${uploadResponse.length}条员工数据。请再次核对，无误则确认导入~`} type="success"
          showIcon/>
      );
      columns.pop();
    }
    console.log(ifError);
    console.log(uploadResponse);

    return (
      <Modal
        title="导入通讯录"
        visible={this.state.visible}
        onOk={this.handleOk.bind(this, ifError)}
        okText={`${ifError ? "有误，稍后上传" : "无误，确认导入"}`}
        onCancel={this.handleCancel}
        cancelText="取消"
        width='1200px'
      >
        {alert}
        <Table columns={columns}
               dataSource={uploadResponse}
               pagination={pageInitStudent}
               scroll={{ x: '130%' }}
               style={{marginTop: '16px'}}/>
      </Modal>
    );
  }

  //加载格式错误提示框
  renderUploadFormat = () => {

    const columnsFormat = [{
      title: '序号',
      dataIndex: 'index',
      key: 'index',
    }, {
      title: '错误提示',
      dataIndex: 'info',
      key: 'info',
    }];

    const dataFormat = this.state.dataFormat;

    let [total, ...errorInfos] = dataFormat.split("<br>");
    if (errorInfos.length !== 1) {
      errorInfos.pop();
    }
    errorInfos = errorInfos.map((val, key) => {
      return {
        index: key + 1,
        info: val,
        key
      };
    });
    return (
      <Modal
        title="导入通讯录"
        visible={this.state.visibleFormat}
        onOk={this.handleFormatOk}
        okText="有误，稍后上传"
        onCancel={this.handleFormatOk}
        cancelText=""
      >
        <Alert
          message={`本次上传失败，共 ${total} 条员工数据，其中有 ${errorInfos.length} 条员工的信息格式校验有误。请核对，若有误，则调整 excel`} type="error"
          showIcon/>
        <Table columns={columnsFormat}
               dataSource={errorInfos}
               pagination={pageInitStudent}
               style={{marginTop: '16px'}}/>
      </Modal>
    );
  }

  render() {
    return (
      <Container>
        {/* <header className="password-header">企业专属二维码</header>
        <div className="enterprise-two-dimensional-code">
          <div className="two-dimensional-code-title">
                        <span className="two-dimensional-code-con">
                            <Icon type="export" style={{marginRight: "8px"}}/>
                            分享给员工
                        </span>
            <b className="two-dimensional-code-dashed"/>
            <span className="enterprise-two-dimensional-code-con">
                            <Icon type="scan" style={{marginRight: "8px"}}/>
                            员工扫码
                        </span>
            <b className="two-dimensional-code-dashed"/>
            <span className="enterprise-two-dimensional-code-con">
                            <Icon type="edit" style={{marginRight: "8px"}}/>
                            进入H5界面填写信息
                        </span>
            <b className="two-dimensional-code-dashed"/>
            <span className="enterprise-two-dimensional-code-con">
                            <Icon type="check-circle-o" style={{marginRight: "8px"}}/>
                            提交
                        </span>
            <b className="two-dimensional-code-dashed"/>
            <span className="enterprise-two-dimensional-code-con">
                            <Icon type="user" style={{marginRight: "8px"}}/>
                            审核入职
                        </span>
          </div>
          <div className="current-two-dimensional-code">
            <div className="two-dimensional-code-img">
              <img src={TwoDimensionCode} alt=""/>
            </div>
            <div className="enterprise-code">
              <span>企业码：</span>
              <span>sn2999719</span>
            </div>
            <Button className="save-two-dimensional-code">保存二维码</Button>
          </div>
        </div> */}

        <header className="password-header" style={{marginTop: 30}}>导入员工基本信息</header>
        <div className="employee-content">
          <Steps direction="vertical" size="small" current={0}>
            <Step title="下载员工信息模板，批量填写员工信息" description={this.handleClickLink()}/>
            <Step title="上传填写好的员工信息表" description={this.handleClickUpload()}/>
          </Steps>
        </div>

        <div className="employee-upload">
          {/* <Button type="primary" onClick={this.showModal}>确认上传</Button> */}
          {/* 导入通讯录弹窗 */}
          {this.renderUploadResult()}

          {/*格式错误提示框*/}
          {this.renderUploadFormat()}
        </div>
      </Container>
    );
  }
}

const pageInitStudent = {
  defaultPageSize: 10,
  showQuickJumper: true,
  pageSizeOptions: ["10", "20", '50'],
  showSizeChanger: true
};


/*********************样式*************************** */
const Container = style.div`{
    .password-header{
        font-size: 20px;
        color: #333333;
        padding-bottom:16px;
        border-bottom:1px solid #e9e9e9;
    }
    .employee-content{
        margin-top: 16px;
        border: 1px solid #e9e9e9;
        border-radius: 5px;
        padding: 16px 24px;
        .ant-steps .ant-steps-item.ant-steps-status-process .ant-steps-head-inner{
            border-color: rgba(0, 0, 0, 0.25);
            background-color: #fff;
            .ant-steps-icon{
            color: rgba(0, 0, 0, 0.25);
            }
        }
        button.ant-btn{
            margin-top: 10px;
        }
    }
    .employee-upload{
        width: 88px;
        margin: 16px 0 24px 66px;

    }

    .two-dimensional-code-title{
        margin:24px 0;
    }
    .two-dimensional-code-title{
        margin-left:18px;
    }
    .enterprise-two-dimensional-code-con{
        display:inline-block;
    }
    .two-dimensional-code-dashed{
        position: relative;
        bottom: 6px;
        display:inline-block;
        width:17px;
        height:14px;
        border-bottom: 1px dashed #e9e9e9;
        margin:0 8px;
    }

    .current-two-dimensional-code{
        margin-left:66px;
        .enterprise-code{
            color: #87D068;
            margin:16px 0 21px 0;
        }
        .save-two-dimensional-code{
            width:140px;
            color: #0F71FF;
            border-color: #0F71FF;
        }
    }
    .two-dimensional-code-img{
        width:140px;
        height:140px;
        padding: 9px;
        border: 1px solid #e9e9e9;
    }
}`;
